import json
import logging
from enum import IntEnum
from typing import Optional, List, Any

from pydantic import BaseModel, Field, model_validator


class ConditionEnum(IntEnum):
    """判断条件枚举"""

    # 或者
    or_else = 0
    # 而且
    and_also = 1


class OperatorsEnum(IntEnum):
    """运算符枚举"""

    # 没有，不执行任何操作
    none = 0
    # 等于 =
    equal = 1
    # 不等于 !=
    not_equal = 2
    # 大于 >
    greater_than = 3
    # 大于等于 >=
    greater_than_or_equal_to = 4
    # 小于 <
    less_than = 5
    # 小于等于 <=
    less_than_or_equal_to = 6
    # 包含
    contains = 7
    # 不包含
    not_contains = 8
    # 以什么开始
    starts_with = 9
    # 以什么结束
    ends_with = 10
    # 在范围以内
    range = 11
    # 在范围以外
    out_range = 12


class QueryCondition(BaseModel):
    """动态查询条件模型"""

    field: str = Field(description="条件参数字段名")
    operator: OperatorsEnum = Field(description="运算符")
    value: Any = Field(description="默认条件参数值")
    second_value: Optional[Any] = Field(
        default=None, description="用于范围查询的第二个值"
    )


class BaseQueryIn(BaseModel):
    """动态查询条件输入"""

    sort: str = Field(default="create_datetime", description="排序字段，默认为创建时间")
    order: bool = Field(default=True, description="顺序，默认为True")
    condition_relation: Optional[ConditionEnum] = Field(
        default=None, description="查询条件关系"
    )
    query_conditions: Optional[List[QueryCondition]] = Field(
        default=[], description="查询条件列表"
    )

    @model_validator(mode="before")
    @classmethod
    def pre_process_query_conditions(cls, data: Any) -> Any:
        if isinstance(data, dict):

            if "query_conditions" in data and isinstance(
                data["query_conditions"], list
            ):
                processed_conditions = []
                for item in data["query_conditions"]:
                    if isinstance(item, str):
                        try:
                            parsed = json.loads(item)
                            processed_conditions.append(parsed)
                        except json.JSONDecodeError as e:
                            logging.warning(f"解析查询条件失败：{item}，错误：{e}")
                            continue
                    else:
                        processed_conditions.append(item)

                data["query_conditions"] = processed_conditions

        return data


